<template>
  <div>
     <h3 class="examTitle">组卷信息</h3>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>
          <el-button type="primary" icon="el-icon-plus" @click="addQuestion">添加题库</el-button>
        </span>
        <el-button style="float: right;color: red;font-size: 16px; font-weight: bold; padding: 3px 0" type="text">试卷总分：{{examineForm.totalPoints}}分</el-button>
      </div>

      <el-table
        :data="tableData"
        style="width: 100%"
        >
        <el-table-column
          prop="questionBlankId"
          label="题库"
        >
          <template slot-scope="scope">
            <el-select v-model="scope.row.questionBlankId" @change="(value)=> selectQuestionBank(value,scope.$index)" filterable placeholder="选择或搜索题库">
              <el-option
                v-for="item in questionBanks"
                :key="item.id"
                :label="item.questionBlankName"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>



        <el-table-column
          prop="name"
          label="单选数量"
          >
          <template slot-scope="scope">
            <el-row>
              <el-col :span="12">
                <el-input-number @change="calculateTotalScore" :controls="false" style="width:100%" v-model="scope.row.singleChoiceSelectCount" :min="0" :max="scope.row.singleChoiceTotal"></el-input-number>
              </el-col>
              <el-col :span="12">
                <span>/{{scope.row.singleChoiceTotal}}</span>
              </el-col>
            </el-row>
          </template>

        </el-table-column>
        <el-table-column
          prop="singleChoiceScore"
          label="单选分数"
          >
          <template slot-scope="scope">
            <el-input-number @change="calculateTotalScore"  :controls="false" style="width:100%" v-model="scope.row.singleChoiceScore" :min="0" :max="100"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column
          prop="city"
          label="多选数量"
          >
          <template slot-scope="scope">
            <el-row>
              <el-col :span="12">
                <el-input-number @change="calculateTotalScore"  :controls="false" style="width:100%" v-model="scope.row.multipleChoiceSelectCount" :min="0" :max="scope.row.multipleChoiceTotal"></el-input-number>
              </el-col>
              <el-col :span="12">
                <span>/{{scope.row.multipleChoiceTotal}}</span>
              </el-col>
            </el-row>
          </template>
        </el-table-column>


        <el-table-column
          prop="multipleChoiceScore"
          label="多选分数"
          >
          <template slot-scope="scope">
            <el-input-number @change="calculateTotalScore"  :controls="false" style="width:100%" v-model="scope.row.multipleChoiceScore" :min="0" :max="100"></el-input-number>
          </template>

        </el-table-column>


        <el-table-column
          prop="multipleChoiceScore"
          label="判断题数量"
        >
          <template slot-scope="scope">
            <el-row>
              <el-col :span="12">
                <el-input-number @change="calculateTotalScore"  :controls="false" style="width:100%" v-model="scope.row.trueorfalseQuestionsSelectCount" :min="0" :max="scope.row.trueorfalseQuestionsTotal"></el-input-number>
              </el-col>
              <el-col :span="12">
                <span>/{{scope.row.trueorfalseQuestionsTotal}}</span>
              </el-col>
            </el-row>
          </template>

        </el-table-column>
        <el-table-column
          prop="multipleChoiceScore"
          label="判断题分数"
        >
          <template slot-scope="scope">
            <el-input-number  @change="calculateTotalScore"    :controls="false" style="width:100%" v-model="scope.row.trueorfalseQuestionsScore" :min="0" :max="100"></el-input-number>

          </template>

        </el-table-column>


        <el-table-column
          label="操作"
          >
          <template slot-scope="scope">
            <el-button type="danger" @click="delHandleClick(scope.$index)" icon="el-icon-delete" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <h3 class="examTitle">考试配置</h3>
    <el-card class="box-card">
      <el-form ref="examineForm" :model="examineForm"  :rules="rules" label-width="80px">
        <el-form-item label="考试名称" prop="examName">
          <el-input v-model="examineForm.examName" placeholder="请输入考试名称" />
        </el-form-item>
        <el-form-item label="考试描述" prop="examDescribe">
          <el-input type="textarea" v-model="examineForm.examDescribe" placeholder="请输入考试描述" />
        </el-form-item>
        <el-form-item label="总分数" prop="totalPoints">
          <el-input disabled v-model="examineForm.totalPoints" placeholder="请输入总分数" />
        </el-form-item>
        <el-form-item label="及格分数" prop="passMark">
          <el-input-number v-model="examineForm.passMark" placeholder="请输入及格分数" />
        </el-form-item>
        <el-form-item label="考试时长" prop="examDuration">
          <el-input-number v-model="examineForm.examDuration" placeholder="请输入考试时长" />
        </el-form-item>

        <el-form-item label="是否限时" prop="isTimeLimit">
          <el-checkbox v-model="examineForm.isTimeLimit"></el-checkbox>
        </el-form-item>

        <div v-if="examineForm.isTimeLimit">
          <el-form-item label="考试时间" prop="examTime">
            <el-date-picker
              v-model="examTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>

        </div>

<!--        <el-form-item label="考试开始时间" prop="examStartTime">-->
<!--          <el-date-picker clearable-->
<!--                          v-model="examineForm.examStartTime"-->
<!--                          type="date"-->
<!--                          value-format="yyyy-MM-dd"-->
<!--                          placeholder="请选择考试开始时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="考试结束时间" prop="examStopTime">-->
<!--          <el-date-picker clearable-->
<!--                          v-model="examineForm.examStopTime"-->
<!--                          type="date"-->
<!--                          value-format="yyyy-MM-dd"-->
<!--                          placeholder="请选择考试结束时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->

      </el-form>

    </el-card>
   <h3 class="examTitle">权限配置</h3>

    <el-card  class="box-card">
      <el-radio-group v-model="examineForm.examType" size="small">
        <el-radio @change="selectExamType"  v-for="dict in dict.type.exam_examine_type" :label="dict.value" border >{{dict.label}}</el-radio>
      </el-radio-group>

      <div v-if="examineForm.examType==0">
        <el-tag type="warning" style="width: 100%;margin-top: 20px" >开放的，任何人都可以进行考试！</el-tag>
      </div>

      <div v-if="examineForm.examType==1">
        <el-input
          v-model="deptName"
          placeholder="请输入部门名称"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="width: 100%;margin-top: 20px;margin-bottom: 20px"
        />

        <el-tree
          :data="deptOptions"
          :props="defaultProps"
          :expand-on-click-node="false"
          show-checkbox
          :filter-node-method="filterNode"
          ref="tree"
          node-key="id"
          default-expand-all
          highlight-current
        />
      </div>


    </el-card>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm('examineForm')">保 存</el-button>
    </div>
  </div>
</template>

<script>
import {getQuestionBankAllList,allListNotInIds} from "@/api/exam/questionBank";
import {deptTreeSelect} from "@/api/system/user";
import {addExamine} from "@/api/exam/examine";
export default {
  name: "AddExamNew",
  dicts: ['exam_examine_type'],
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    return {
      tableData: [],
      questionBanks:[],
      examTime:[],
      examineForm:{
        examGeneratingPaper: [],
        totalPoints: 0,
        passMark: 0,
        examDuration: 0,
        deptIds: ""
      },
      rules:{
        examName: [
          { required: true, message: "考试名称不能为空", trigger: "blur" }
        ],
      },
      deptOptions: undefined,
      deptName: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },

    }

  },
  created() {
    getQuestionBankAllList().then(res => {
      console.info(res,"getQuestionBankAllList-->")
      this.questionBanks = res.data
    })
  },
  methods: {

    submitForm(formName) {
      console.info(formName,"formName-->")

      console.info(this.$refs[formName],"this.$refs[formName]-->");
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.examineForm.examGeneratingPaper = this.tableData;
          this.examineForm.deptIds = this.$refs.tree.getCheckedKeys().join(",");
          this.examineForm.isTimeLimit = this.examineForm.isTimeLimit ? 1 : 0;
          this.examineForm.examStartTime = this.examTime[0];
          this.examineForm.examStopTime = this.examTime[1];
          console.info(this.examineForm,"this.examineForm-->")


          addExamine(this.examineForm).then(response => {
            console.info(response,"addExamine-->")
            if (response.code === 200) {
              this.$message({
                message: "新增成功",
                type: "success"
              });
              this.$router.push({ path: "/exam/examine/index" });
            } else {
              this.$message({
                message: response.msg,
                type: "error"
              });
            }
          })
        } else {
          this.$message.error(`请检查提交的表单内容!`);
          return false;
        }
      });
    },
    selectExamType(val){
      if(val==1){
        this.getDeptTree();
      }
    },
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },

    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    calculateTotalScore(val){
      this.examineForm.totalPoints = 0;
      console.info(val,"calculateTotalScore-->")
      this.tableData.forEach(item => {
        this.examineForm.totalPoints += item.singleChoiceScore * item.singleChoiceSelectCount + item.multipleChoiceScore * item.multipleChoiceSelectCount + item.trueorfalseQuestionsScore * item.trueorfalseQuestionsSelectCount
      })

    },
    selectQuestionBank(val,index){
      console.info(val,"selectQuestionBank val-->")
      console.info(index,"selectQuestionBank index-->")
      this.questionBanks.forEach(item => {
        if(item.id == val){

          this.tableData[index].questionBlankId = item.id;
          this.tableData[index].questionBlankName = item.questionBlankName;

          //单选题
          this.tableData[index].singleChoiceTotal = item.singleChoice
          this.tableData[index].singleChoiceSelectCount = 0;
          this.tableData[index].singleChoiceScore = 0;
          //多选题
          this.tableData[index].multipleChoiceTotal = item.multipleChoice
          this.tableData[index].multipleChoiceSelectCount = 0;
          this.tableData[index].multipleChoiceScore = 0;

          //判断题
          this.tableData[index].trueorfalseQuestionsTotal = item.trueorfalseQuestions
          this.tableData[index].trueorfalseQuestionsSelectCount = 0;
          this.tableData[index].trueorfalseQuestionsScore = 0;


        }
      })

    },
    delHandleClick(index){
      console.info(index,"delHandleClick index-->")
      this.tableData.splice(index,1)

      this.resetQuestionBanks();

    },
    //重置题库
    resetQuestionBanks(){
      let questionBankIds = [];
      if(this.tableData.length > 0){
        this.tableData.forEach(item => {
          questionBankIds.push(item.questionBlankId)
        })
        console.info(questionBankIds,"questionBankIds-->");
        allListNotInIds(questionBankIds).then(res => {
          this.questionBanks = res.data
        })
      }else{
        allListNotInIds(questionBankIds).then(res => {
          this.questionBanks = res.data
        })
      }
    },
    addQuestion(){
      this.resetQuestionBanks();
      this.tableData.push({})
    }
  }
}
</script>

<style scoped>
  .examTitle{
    margin-top: 20px;
    margin-left: 20px;
  }
</style>
